package cn.itsource.basic.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

//文件上传
@RestController
    @RequestMapping("/fastdfs")
    public class FileUploadController {

        @PostMapping("/upload")
        public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
            try {
                String fileName = file.getOriginalFilename();//qq123.jpg
                String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
                String result = FastdfsUtil.upload(file.getBytes(), extName);
                return AjaxResult.me().setResultObj(result);
            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
            }
        }

        @DeleteMapping
        public AjaxResult delete(@RequestParam(value = "path",required = true) String path){
            //   /group1/M00/01/28/CgAIC2Ls0xyARkv7AAD1Sgb3qiI779.jpg
            try {
                String pathTmp = path.substring(1); // group1/M00/01/28/CgAIC2Ls0xyARkv7AAD1Sgb3qiI779.jpg
                String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
                String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// M00/01/28/CgAIC2Ls0xyARkv7AAD1Sgb3qiI779.jpg
                FastdfsUtil.delete(groupName,remotePath);
                return AjaxResult.me();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
            }
        }
    }


